package com.iflysse.bbs.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.iflysse.bbs.dao.UserDao;
import com.iflysse.bbs.model.UserInfo;
import com.iflysse.bbs.util.JdbcUtil;

public class UserDaoImpl implements UserDao {
	private QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
	
	@Override
	public UserInfo getUser(String account, String password) {
		UserInfo user = null;
		String sql = "select * from user where account=? and password=?";
		Object[] params = {account,password};
		try {
			user = runner.query(sql, new BeanHandler<UserInfo>(UserInfo.class),params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public boolean updatePwd(int userId, String newPwd) {
		boolean flag = false;
		String sql = "update user set password=? where id=?";
		Object[] params = {newPwd,userId};
		try {
			int row = runner.update(sql, params);
			flag = row > 0 ? true : false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public boolean add(UserInfo user) {
		boolean flag = false;
		String sql = "insert into user(name,account,password,email) values(?,?,?,?)";
		Object[] params = {user.getName(),user.getAccount(),user.getPassword(),user.getEmail()};
		try {
			int row = runner.update(sql, params);
			flag = row > 0 ? true : false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public UserInfo getUser(int id) {
		UserInfo user = null;
		String sql = "select * from user where id=?";
		try {
			user = runner.query(sql, new BeanHandler<UserInfo>(UserInfo.class),id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

}
